package com.hspedu.encap;

public class Encapsulation01 {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("jack");
        person.setAge(30);
        person.setSalary(30000);
        System.out.println(person.info());

        //如果我们自己使用构造器指定属性
        Person smith = new Person("smith", 20, 50000);
        System.out.println("=====smith的信息=====");
        System.out.println(smith.info());

    }
}

/*
不能随便查看人的年龄，工资等隐私，并对设置的年龄进行合理的验证。年龄合理就设置，否则默认
年龄，必须在1-120，年龄工资不能直接name的长度在2-6字符之间
 */
class Person {

    public String name;
    private int age;
    private double salary;

    //构造器
    public Person() {
    }

    public Person(String name, int age, double salary) {
//        this.name = name;
//        this.age = age;
//        this.salary = salary;
        setName(name);
        setAge(age);
        setSalary(salary);
    }

    public void setName(String name) {
        if (name.length() >= 2 && name.length() <= 6) {
            this.name = name;
        } else {
            System.out.println("名字的长度不对，需要2-6个字符，给默认名字");
            this.name = "无名人";
        }

    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age >= 1 && age <= 120) {
            this.age = age;
        } else {
            System.out.println("你设置的年龄不对，需要在1-120，给默认年龄18");
            this.age = 18;//
        }

    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    //返回属性的方法
    public String info() {
        return "信息为 name=" + name + " age=" + age + " salary=" + salary;
    }
}

